package com.zqq.aidl;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private IMyAidlInterface iMyAidlInterface;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent intent = new Intent("com.zqq.aidl.server");
        intent.setPackage(this.getPackageName());//com.zqq.aidl

        bindService(intent, new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                System.out.println("*******************服务已经连接！！！");
                //获取iMyAidlInterface对象，然后在onClick中调用iMyAidlInterface.getName()。
                iMyAidlInterface = IMyAidlInterface.Stub.asInterface(service);
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                System.out.println("*******************服务关闭连接！！");
            }
        }, BIND_AUTO_CREATE);
    }


    /**
     * 通过隐式意图来绑定service，在onServiceConnected方法中通过IMyAidlInterface.Stub.asInterface(service)
     * 获取iMyAidlInterface对象，然后在onClick中调用iMyAidlInterface.getName()。
     *
     * @param view
     */
    public void onClick(View view) {
        try {
            String name = iMyAidlInterface.getName();
            String user = iMyAidlInterface.getUserName().name;
            Toast.makeText(MainActivity.this, name + "-" + user, Toast.LENGTH_SHORT).show();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        unbindService(conn);
    }
}
